#include "Pinea.h"

// 全局窗口和渲染器指针，用于在整个程序中访问 SDL 窗口和渲染器
// SDL_Window*：SDL 窗口对象指针，管理窗口的创建、显示、尺寸等属性
// SDL_Renderer*：SDL 渲染器指针，用于执行绘制操作
SDL_Window* window;
SDL_Renderer* renderer;

void pineaInit(const char* title, int width, int height) {
  // 初始化 SDL 的视频子系统
	SDL_Init(SDL_INIT_VIDEO);
	window = SDL_CreateWindow(title, width, height, SDL_WINDOW_HIDDEN);
	renderer = SDL_CreateRenderer(window, nullptr);
  // 设置渲染器的混合模式为 alpha 混合
  // SDL_BLENDMODE_BLEND：启用透明度混合，使绘制的图形 / 图像支持半透明效果
	SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
}

void pineaQuit() {
	SDL_DestroyRenderer(renderer);
	SDL_DestroyWindow(window);
}

void pineaShow() {
	SDL_ShowWindow(window);
}

bool pineaPollEvent(PineaEvent* event) {
	SDL_Event e;
	if (SDL_PollEvent(&e)) {
		event->type = e.type;
		event->key = e.key.key;
		return true;
	}
	return false;
}

void pineaClear(const PineaColor* color) {
	SDL_SetRenderDrawColor(renderer, color->r, color->g, color->b, color->a);
	SDL_RenderClear(renderer);
}

void pineaRender() {
	SDL_RenderPresent(renderer);
}

void pineaFillRect(const PineaRect* rect, const PineaColor* color) {
	SDL_SetRenderDrawColor(renderer, color->r, color->g, color->b, color->a);
	SDL_RenderFillRect(renderer, rect);
}

void pineaLoadImage(const char* path, SDLPineaImage* sdlPineaImage) {
	SDL_Texture* image = (SDL_Texture*)IMG_LoadTexture(renderer, path);
	SDL_SetTextureScaleMode(image, SDL_SCALEMODE_NEAREST);
	sdlPineaImage->imagePointer = image;
	sdlPineaImage->width = image->w;
	sdlPineaImage->height = image->h;
}

void pineaDrawImage(SDL_Texture* image, const PineaRect* srcRect, const PineaRect* dstRect, double angle, int flip) {
	SDL_RenderTextureRotated(renderer, image, srcRect, dstRect, angle, nullptr, (SDL_FlipMode)flip);
}

void pineaDropImage(SDL_Texture* image) {
	SDL_DestroyTexture(image);
}
